//
//  SearchViewController.m
//  AllFamily
//
//  Created by chirui on 2018/6/1.
//  Copyright © 2018年 Shui. All rights reserved.
//

#import "SearchViewController.h"
#import "MyCenterCViewCell.h"
#import "MyCenterCollectionReusableView.h"
#import "SearchView.h"

@interface SearchViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,SDCycleScrollViewDelegate,UITextFieldDelegate>
{
    UICollectionView * _collectionView;

    NSMutableArray * _dataArray;
    int _page;
    int _totailPage;
    
    NSString * keyWordStr;
     UITextField * searchText;
    UIView *  noBodyView;
}

@end

@implementation SearchViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    _page = 1;
    _dataArray= @[].mutableCopy;

    self.automaticallyAdjustsScrollViewInsets = NO;
    
    //    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"img_nav_bg"] forBarMetrics:UIBarMetricsDefault];
    self.view.backgroundColor =[UIColor groupTableViewBackgroundColor];
    [self creatCollectionView];

    self.navigationItem.titleView =    [SearchView  creatSearchTextFieldForDelegate:self Placeholder:@"请输入商品名称"];
     noBodyView = [NothingMessageView creatNothingMessageViewFrame:CGRectMake(WIDTH/2-100, (HEIGHT-64)/2-100, 200, 200) andMessageStr:@"还没有相关内容~" onView:nil];
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem rightItemWithTitle:@" 搜索" target:self action:@selector(searchBtnClick)];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithIcon:@"icon_nav_renter" target:self action:@selector(backBtnClick)];
}

-(void)backBtnClick{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)searchBtnClick{
    
    [searchText resignFirstResponder];
    
    keyWordStr = searchText.text;
    if (keyWordStr.length<=0) {
        
        SHuiMBhudTextTimeStr(@"请输入商品名称");
        return;
    }
    _page = 1;
    [self getNewsListDataFor:keyWordStr];
}

-(void)textFieldDidBeginEditing:(UITextField *)textField{
    
    searchText = textField;
    
}

#pragma creatCollectionView

-(void)creatCollectionView {
    
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT-64+20) collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:_collectionView];
    _collectionView.showsVerticalScrollIndicator = NO;
    
    MJRefreshNormalHeader * header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        
        _page = 1;
       
        [self getNewsListDataFor:keyWordStr];
    }];
    _collectionView.mj_header = header;
    
    MJRefreshAutoNormalFooter *  footer =[MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _page++;
        [self getNewsListDataFor:keyWordStr];
        
    }];
    
    footer.automaticallyRefresh = YES;
    _collectionView.mj_footer =footer;
    
    if (_dataArray.count>10) {
        _collectionView.mj_footer.hidden = NO;
    }else {
        
        _collectionView.mj_footer.hidden = YES;
    }
    
    
    //注册cell类
    [_collectionView registerNib:[UINib nibWithNibName:@"MyCenterCViewCell" bundle:nil] forCellWithReuseIdentifier:@"MyCenterCViewCell"];
    
    //    注册header类
    [_collectionView registerClass:[MyCenterCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"MyCenterCollectionReusableView"];
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    
    return _dataArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    NSDictionary * dic = _dataArray[indexPath.row];
    MyCenterCViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCenterCViewCell" forIndexPath:indexPath];
    cell.clipsToBounds = NO;
    
    UILabel *tagLabel =[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 65, 20)];
    tagLabel.font =[UIFont systemFontOfSize:14];
    tagLabel.text =@"公益商品";
    tagLabel.textColor =[UIColor whiteColor];
    tagLabel.backgroundColor =  Color(58, 168, 38);
    [cell.goodsImage addSubview:tagLabel];
    if ([dic[@"is_public"] isEqualToString:@"yes"]) {
        
        tagLabel.hidden = NO;
    }else {
        
        tagLabel.hidden = YES;
    }
    
    [cell.goodsImage sd_setImageWithURL:ImageUrl(dic[@"cover_photo"]) placeholderImage:ImageName(@"img_new_default")];
    
    cell.gooseName.frame = CGRectMake(6, CGRectGetMaxY(cell.goodsImage.frame)+5, (WIDTH-10)/2-12, 20);
    cell.gooseName.text = dic[@"product_name"];
    
    cell.gooseName.numberOfLines = 2;
    [cell.gooseName sizeToFit];
    
    cell.scoreLabel.text = [NSString stringWithFormat:@"￥%@",dic[@"price"]];
    return cell;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary * Dic = _dataArray[indexPath.row];
    GoodsDetailsViewController * goods =[[GoodsDetailsViewController alloc]init];
    goods.goodsId = [NSString stringWithFormat:@"%@",Dic[@"id"]];
    goods.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:goods animated:YES];
    
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //    第一个参数是宽，第二个参数是高 5s  1.8   6 1.6   6p
    float height;
    if (ISP5||ISP4) {
        height = 1.5;
    }else if (ISP6){
        height = 1.3;
        
    }else if (ISP6P){
        height = 1.4;
    }else {
        
        height = 1.4;
    }
    
    CGSize size=CGSizeMake((WIDTH-10)/2, (WIDTH-10)/2*height);
    
    return size;
    
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    //上 左 下 右
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

//设置水平间隙   默认10
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

////设置垂直间隙  默认10
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    
    return CGSizeMake(0,0);
}
//设置footer的宽度
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    //第一个参数：水平滑动时footer的宽度
    //第二个参数：垂直滑动时footer的高度
    return CGSizeMake(0, 0);
}

//网络请求 全部商品
-(void)getNewsListDataFor:(NSString *)sortStr{
    
    if (_totailPage != 0) {
        if(_page == _totailPage + 1){
            [_collectionView.mj_footer setState: MJRefreshStateNoMoreData];
            
            return ;
        }
    }
    
    NSDictionary * dic = @{@"page":[NSString stringWithFormat:@"%d",_page],
                           @"perpage":@"10",
                           @"product_name":sortStr
                           };
    
    //    SHuiMBhubNoTimeStr(@"正在加载...");
    [PostNetWorking postNetWorkingStr:RequestUrlStr(get_productList_api) andparameters:dic Success:^(id responseObject) {
        SHuiMBHidleYes;
        if (codeSucess) {
            
            _totailPage = [responseObject[@"datas"][@"total_page"]  intValue];
            if (_page==1) {
                
                if (_dataArray) {
                    
                    [_dataArray removeAllObjects];
                }
                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }else {
                
                if ([responseObject[@"datas"][@"lists"]  isKindOfClass:[NSArray class]]) {
                    
                    for (NSDictionary * dic in responseObject[@"datas"][@"lists"]) {
                        
                        [_dataArray addObject:dic];
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                
                
                if (_dataArray.count>0) {
                    if (_dataArray.count<10) {
                        noBodyView.hidden = YES;
                        _collectionView.mj_footer.hidden = YES;
                    }
                }else {
                    noBodyView.hidden = NO;
                    _collectionView.mj_footer.hidden = YES;
                    [self.view addSubview:noBodyView];
                }
                [_collectionView.mj_header endRefreshing];
                [_collectionView.mj_footer endRefreshing];
                [_collectionView reloadData];
                
            });
        }else {
            
            SHuiMBhudTextTimeStr(responseObject[@"mark"]);
        }
        
    } failed:^(NSError *error) {
        
        SHuiMBHidleYes;
        SHuiMBhudTextTimeStr(@"网络错误请重试！");
    }];
    
}


@end
